import { Context, Next } from 'koa';
import { getRedisClient } from '../database/redis';
import config from '../config';
import { error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';
import { consoleLog, LogType, LogLevel } from '../utils/logger';

/**
 * 基于IP和API路径的速率限制中间件
 * 同一个API在同一个IP下，60秒内最多60次
 */
export async function rateLimitMiddleware(ctx: Context, next: Next): Promise<void> {
  const ip = ctx.ip || ctx.request.ip || 'unknown';
  const path = ctx.path || ctx.url.split('?')[0] || 'unknown';
  const key = `rate_limit:${ip}:${path}`;
  const redis = getRedisClient();
  
  try {
    const current = await redis.incr(key);
    
    if (current === 1) {
      // 第一次请求，设置过期时间
      await redis.expire(key, Math.ceil(config.rateLimit.window / 1000));
    }
    
    if (current > config.rateLimit.max) {
      error(ctx, ResponseCode.TOO_MANY_REQUESTS);
      return;
    }
    
    await next();
  } catch (err) {
    // Redis错误时，允许请求通过，避免Redis故障影响服务
    consoleLog(
      LogType.REDIS,
      LogLevel.ERROR,
      'Rate limit Redis error',
      {
        error: err,
        ip,
      }
    );
    await next();
  }
}

